import { forEach, startsWith } from 'lodash';
import { Row, Col, Input, Button, message, Table } from 'antd';

import styles from '../TableList.less';

export function generateScoreMap(phaseCode, scoreList) {
  var scoreMap = {};
  scoreList.map(element => {
    if (phaseCode && phaseCode !== element.phaseCode) {
      return;
    }
    const fenzu = element.fenzuName;
    const gamePos1 = element.gamePosName1;
    const gamePos2 = element.gamePosName2;
    if (fenzu !== '') {
      if (!scoreMap[fenzu]) {
        scoreMap[fenzu] = {};
        scoreMap[fenzu].columns = [];
        scoreMap[fenzu].data = [];
        scoreMap[fenzu].scores = {};
      }

      if (!listContains(scoreMap[fenzu].columns, gamePos1)) {
        scoreMap[fenzu].columns.push(gamePos1);
      }
      if (!listContains(scoreMap[fenzu].columns, gamePos2)) {
        scoreMap[fenzu].columns.push(gamePos2);
      }

      if (!scoreMap[fenzu].scores[gamePos1]) {
        scoreMap[fenzu].scores[gamePos1] = {};
        if (gamePos1) {
          const fenzuName = gamePos1.substring(0, 1);
          const fenzuSeq = gamePos1.substring(1);
          scoreMap[fenzu].scores[gamePos1].fenzuName = fenzuName;
          scoreMap[fenzu].scores[gamePos1].fenzuSeq = fenzuSeq;
        }
        scoreMap[fenzu].scores[gamePos1].gamePos = gamePos1;
        scoreMap[fenzu].scores[gamePos1].athlete = element.athlethList1;
        scoreMap[fenzu].scores[gamePos1].chang = 0;
        scoreMap[fenzu].scores[gamePos1].wins = 0;
        scoreMap[fenzu].scores[gamePos1].odds = 0;
      }

      if (!scoreMap[fenzu].scores[gamePos2]) {
        scoreMap[fenzu].scores[gamePos2] = {};
        if (gamePos2) {
          const fenzuName = gamePos2.substring(0, 1);
          const fenzuSeq = gamePos2.substring(1);
          scoreMap[fenzu].scores[gamePos2].fenzuName = fenzuName;
          scoreMap[fenzu].scores[gamePos2].fenzuSeq = fenzuSeq;
        }
        scoreMap[fenzu].scores[gamePos2].gamePos = gamePos2;
        scoreMap[fenzu].scores[gamePos2].athlete = element.athlethList2;
        scoreMap[fenzu].scores[gamePos2].chang = 0;
        scoreMap[fenzu].scores[gamePos2].wins = 0;
        scoreMap[fenzu].scores[gamePos2].odds = 0;
        //scoreMap[fenzu].scores[gamePos2].matchInfo = element
      }
      var pos1Win = 0;
      var pos2Win = 0;
      var winflag = false;
      const showScoreArray = [];
      const fenzuSeq1 = gamePos1.substring(1);
      const fenzuSeq2 = gamePos2.substring(1);
      element.scoreList.map(value => {
        if (winflag) {
          return;
        }

        if (value.score1 && value.score2) {
          if (fenzuSeq1 < fenzuSeq2) {
            showScoreArray.push({ score1: value.score1, score2: value.score2 });
          } else {
            showScoreArray.push({ score1: value.score2, score2: value.score1 });
          }

          if (value.score1 > value.score2) {
            scoreMap[fenzu].scores[gamePos1].wins = scoreMap[fenzu].scores[gamePos1].wins + 1;
            scoreMap[fenzu].scores[gamePos2].wins = scoreMap[fenzu].scores[gamePos2].wins - 1;
            pos1Win++;
          } else {
            scoreMap[fenzu].scores[gamePos1].wins = scoreMap[fenzu].scores[gamePos1].wins - 1;
            scoreMap[fenzu].scores[gamePos2].wins = scoreMap[fenzu].scores[gamePos2].wins + 1;
            pos2Win++;
          }
          scoreMap[fenzu].scores[gamePos1].odds =
            scoreMap[fenzu].scores[gamePos1].odds + value.score1 - value.score2;
          scoreMap[fenzu].scores[gamePos2].odds =
            scoreMap[fenzu].scores[gamePos2].odds + value.score2 - value.score1;
          if (element.scoreList.length === 1) {
            scoreMap[fenzu].scores[gamePos1][gamePos2] = {
              matchInfo: element,
              score1: value.score1,
              score2: value.score2,
            };
            scoreMap[fenzu].scores[gamePos2][gamePos1] = {
              score1: value.score2,
              score2: value.score1,
            };
          }
        } else {
          scoreMap[fenzu].calFlag = true;
        }

        if (pos1Win > element.scoreList.length / 2) {
          scoreMap[fenzu].scores[gamePos1].chang = scoreMap[fenzu].scores[gamePos1].chang + 1;
          winflag = true;
        }

        if (pos2Win > element.scoreList.length / 2) {
          scoreMap[fenzu].scores[gamePos2].chang = scoreMap[fenzu].scores[gamePos2].chang + 1;
          winflag = true;
        }
      });
      if (element.scoreList.length > 1) {
        if (fenzuSeq1 < fenzuSeq2) {
          scoreMap[fenzu].scores[gamePos1][gamePos2] = {
            flag: 'table',
            list: showScoreArray,
            matchInfo: element,
          };
          scoreMap[fenzu].scores[gamePos2][gamePos1] = {
            score1: pos2Win,
            score2: pos1Win,
          };
        } else {
          scoreMap[fenzu].scores[gamePos1][gamePos2] = {
            matchInfo: element,
            score1: pos1Win,
            score2: pos2Win,
          };
          scoreMap[fenzu].scores[gamePos2][gamePos1] = {
            list: showScoreArray,
            flag: 'table',
            matchInfo: element,
          };
        }
      }
    }
  });

  const comparePos = (obj1, obj2) => {
    var val1 = obj1.fenzuName;
    var val2 = obj2.fenzuName;
    var val3 = parseInt(obj1.fenzuSeq);
    var val4 = parseInt(obj2.fenzuSeq);
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      if (val3 < val4) {
        return -1;
      } else if (val3 > val4) {
        return 1;
      } else {
        return 0;
      }
    }
  };

  const compareScore = (obj2, obj1) => {
    var val1 = obj1.chang;
    var val2 = obj2.chang;
    var val3 = obj1.wins;
    var val4 = obj2.wins;
    var val5 = obj1.odds;
    var val6 = obj2.odds;
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      if (val3 < val4) {
        return -1;
      } else if (val3 > val4) {
        return 1;
      } else {
        if (val5 < val6) {
          return -1;
        } else if (val5 > val6) {
          return 1;
        } else {
          return 0;
        }
      }
    }
  };

  forEach(scoreMap, element => {
    var flag = true;

    forEach(element.scores, value => {
      if (!value.score1) {
        flag = false;
      }
      value[value.gamePos] = { isnull: true };
      element.data.push(value);
    });

    if (!element.calFlag) {
      element.data.sort(compareScore);
      element.data.forEach((element, index) => {
        element.ranking = index + 1;
      });

      element.columns.sort();
      element.data.sort(comparePos);
    } else {
      element.columns.sort();
      element.data.sort(comparePos);
    }
  });

  return scoreMap;
}

function listContains(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}

export function generateScoreTable(phaseCode, scoreList, hadlerScoreInput, isPhaseFinished) {
  const scoreMap = generateScoreMap(phaseCode, scoreList);
  const tables = [];
  forEach(scoreMap, (value, key) => {
    tables.push(
      <Table
        key={key}
        pagination={false}
        bordered
        size="small"
        style={{ marginBottom: 30 }}
        dataSource={value.data}
        columns={generateScoreField(key, value.columns, hadlerScoreInput, isPhaseFinished)}
      />
    );
  });
  return tables;
}

const compareColumn = (obj1, obj2) => {
  if (obj1 && obj2) {
    var val1 = obj1.substring(0, 1);
    var val2 = obj2.substring(0, 1);
    var val3 = parseInt(obj1.substring(1));
    var val4 = parseInt(obj2.substring(1));
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      if (val3 < val4) {
        return -1;
      } else if (val3 > val4) {
        return 1;
      } else {
        return 0;
      }
    }
  } else if (obj1) {
    return -1;
  } else if (obj2) {
    return 1;
  } else {
    return 0;
  }
};

function embScoreTable(list) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      {list.map(value => (
        <div style={{ fontWeight: 'bold', widows: 30, flex: 1 }}>
          {value.score1 ? value.score1 : <span>&nbsp;</span>} :{' '}
          {value.score2 ? value.score2 : <span>&nbsp;</span>}
        </div>
      ))}
    </div>
  );
}

function generateScoreField(key, fieldList, hadlerScoreInput, isPhaseFinished) {
  fieldList.sort(compareColumn);
  const fileds = [
    {
      title: <span style={{ fontSize: 18, color: 'red' }}>{key + '组'}</span>,
      dataIndex: 'gamePos',
      width: 80,
      align: 'center',
    },
    {
      title: '',
      dataIndex: 'athlete',
      width: 150,
      align: 'center',
      render: value => (
        <span>
          {value &&
            value
              .map(value => {
                return value.userName;
              })
              .join(',')}
        </span>
      ),
    },
  ];
  fieldList.forEach(value => {
    fileds.push({
      title: value,
      width: 180,
      className: styles.columnNopadding,
      align: 'center',
      render: (text, obj, index) => {
        return obj[value] ? (
          obj[value].isnull ? (
            <div className={styles.outScore} />
          ) : obj[value].flag === 'table' ? (
            <div>{embScoreTable(obj[value].list)}</div>
          ) : (
            <div style={{ fontWeight: 'bold' }}>
              {obj[value].score1} : {obj[value].score2}
            </div>
          )
        ) : (
          <div />
        );
      },
    });
  });
  fileds.push({
    title: '胜场',
    dataIndex: 'chang',
    align: 'center',
    width: 100,
  });
  fileds.push({
    title: '净胜局',
    dataIndex: 'wins',
    align: 'center',
    width: 100,
  });
  fileds.push({
    title: '净胜分',
    dataIndex: 'odds',
    align: 'center',
    width: 100,
  });

  fileds.push({
    title: '名次',
    dataIndex: 'ranking',
    align: 'center',
  });

  return fileds;
}
